import { useEffect, useCallback } from 'react';
import { useSession } from 'next-auth/react';
//配合AuthProvider组件使用
/**
 * 自定义钩子：跟踪用户活动并定期更新会话活动时间
 * 
 * 使用方法：在布局组件中调用 useSessionActivity()
 */
export const useSessionActivity = () => {
  const { data: session, status } = useSession();
  
  // 更新会话活动时间
  const updateActivity = useCallback(async () => {
    if (status === 'authenticated') {
      try {
        const response = await fetch('/api/auth/session-activity', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
        });
        
        if (response.ok) {
          const data = await response.json();
          console.log('会话活动API响应:', data);
        }
      } catch (error) {
        console.error('更新会话活动时间失败:', error);
      }
    }
  }, [status]);
  
  // 定期更新活动时间（每10分钟）
  useEffect(() => {
    if (status === 'authenticated') {
      const interval = setInterval(() => {
        updateActivity();
      }, 10 * 60 * 1000); // 10分钟更新一次
      
      return () => clearInterval(interval);
    }
  }, [status, updateActivity]);
  
  // 在用户交互时更新活动时间
  useEffect(() => {
    if (status === 'authenticated') {
      const events = ['mousedown', 'keydown', 'touchstart', 'scroll'];
      let lastUpdate = 0;
      const handleUserActivity = () => {
        const now = Date.now();
        if (now - lastUpdate > 30000) { 
          lastUpdate = now;
          updateActivity();
        }
      };
      
      events.forEach(event => {
        window.addEventListener(event, handleUserActivity);
      });
      
      return () => {
        events.forEach(event => {
          window.removeEventListener(event, handleUserActivity);
        });
      };
    }
  }, [status, updateActivity]);
  
  return null;
}; 